<div class="wmm-module">
    <div class="layui-form-item">
        <form id="search-form" class="layui-form" action="javascript:;" lay-filter="search-form">
            <div class="layui-inline">
                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="renders.box(true)"><i
                        class="layui-icon layui-icon-add-circle "></i> 添加策略
                </button>
            </div>
            <div class="layui-inline" style="width:300px" wmm-fb-auth="DEVELOPER">
                <select name="appsId" xm-select="appsId" xm-select-skin="normal">
                    <option value="">选择平台搜索</option>
                </select>
            </div>
            <div class="layui-inline">
                <input type="text" name="policyName" autocomplete="off" lay-verify="required" placeholder="请输入策略名称/描述"
                       class="layui-input"/>
            </div>
            <div class="layui-inline">
                <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm datatable-search"><i
                        class="layui-icon layui-icon-search search-icon"></i>
                    查询
                </button>
            </div>
        </form>
    </div>

    <div class="layui-tab" lay-filter="policy-type">
        <ul class="layui-tab-title">
            <li class="layui-this" wmm-policy-type="">全部</li>
            <li wmm-policy-type="SYSTEM">系统策略</li>
            <li wmm-policy-type="CUSTOM">自定义策略</li>
        </ul>
    </div>

    <div>
        <div id="policy-table"></div>
    </div>
</div>

<template id="tmp-auth-form">
    <form class="layui-form" lay-filter="role-menu-form" action="javascript:;">
        <input type="hidden" value="" name="id"/>
        <div class="layui-form-item">
            <label class="layui-form-label">选择菜单</label>
            <div class="layui-input-block">
                <div id="LAY-auth-tree-index"></div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-sm lay-submit layui-btn-normal" lay-submit
                        lay-filter="LAY-auth-tree-submit">立即提交
                </button>
                <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</template>


<template id="tmp-policy-form">
    <div style="padding:10px">
        <form class="layui-form" lay-filter="policy-form" action="javascript:;">
            <input type="hidden" value="" name="id"/>

            <div class="layui-form-item" wmm-fb-auth="DEVELOPER">
                <label class="layui-form-label">所属平台</label>
                <div class="layui-input-block">
                    <select name="appsId" xm-select="appsIdBox" xm-select-skin="normal">
                        <option value="">所有平台</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">

                <label class="layui-form-label">策略名称<span class="required-star">*</span></label>
                <div class="layui-input-block">
                    <input type="text" name="policyName" lay-verify="required|length" placeholder="策略名称"
                           autocomplete="off"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">说明<span class="required-star">*</span></label>
                <div class="layui-input-block">
                    <input type="text" name="remark" lay-verify="required|length" placeholder="填写名称" autocomplete="off"
                           class="layui-input">
                </div>
            </div>


            <div class="layui-form-item fb-layer-btn">
                <div class="layui-input-block">
                    <button class="layui-btn layui-btn-sm lay-submit layui-btn-normal" lay-submit lay-filter="policy">
                        立即提交
                    </button>
                    <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
</template>

<script>

    new Wmm({

        imports: ["datatable", "form", "api", "sysTools"],

        //页面变量
        vars: {
            table: {}
        },
        init: function () {
            sysTools.filterWmmFbAuth("DEVELOPER");
        },

        methods: {
            //数据转换
            convertMenu: function (arr, current) {
                current = current || [];
                arr.forEach(function (elem) {
                    if (elem.children) {
                        elem.children.forEach(function (child) {
                            child.parentName = elem.menuName;
                        })
                        methods.convertMenu(elem.children, current);
                    }
                    current.push(elem);
                    delete elem;
                });
                return current;
            },
            convertTree: function (list, checkedIdArr) {
                var trees = fb.authtree.listConvert(list, {
                    primaryKey: 'id'
                    , startPid: 0
                    , parentKey: 'pid'
                    , nameKey: 'menuName'
                    , valueKey: 'id'
                    , checkedKey: checkedIdArr
                });
                return trees;
            },
            conditionHideOperation: function () {
                var currentType = vars.table.getQueryObject().policyType;
                //如果不是开发者或类型不是自定义 返回true
                return !sysTools.isDeveloper() && currentType !== "CUSTOM";
            },
        },
        //页面事件注册
        listener: function () {
            if (sysTools.isDeveloper()) {
                var itv = setInterval(function () {
                    if (!layui.formSelects) {
                        return;
                    }
                    layui.formSelects.on('appsId', function (id, vals, val, isAdd, isDisabled) {
                        setTimeout(function () {
                            vars.table.setQueryObject({appsId: utils.toJSONData(document.querySelector("#search-form")).appsId})
                        }, 100);
                    }, true);
                    clearInterval(itv);
                }, 200);
            }

            var form = fb.form;
            form.verify({
                length: function (value) {
                    var maxLength = 64;
                    if (value.length > maxLength) {
                        return '输入字符长度不能超过' + maxLength + '位';
                    }
                },
                length128: function (value) {
                    var maxLength = 128;
                    if (value.length > maxLength) {
                        return '输入字符长度不能超过' + maxLength + '位';
                    }
                },
            });

            form.on('submit(policy)', function (data) {
                var dataObject = data.field;

                if (sysTools.isDeveloper()) {
                    dataObject.appsId = fb.formSelects.value("appsIdBox", "val");
                } else {
                    delete dataObject.appsId;
                }
                if (dataObject.id) {
                    //update
                    fb.api.policy.update(dataObject, function () {
                        layer.closeAll();
                        layer.msg("修改成功");
                        renders.flush();
                    });
                    return;
                }
                //insert
                fb.api.policy.add(dataObject, function () {
                    layer.closeAll();
                    layer.msg("添加成功");
                    renders.flush();
                });
            });


            var element = fb.element;

            element.on('tab(policy-type)', function (data) {
                var type = this.getAttribute("wmm-policy-type");
                vars.table.setQueryObject({policyType: type});
                renders.flush();
            });

            form.on('submit(LAY-auth-tree-submit)', function (obj) {
                var menusId = fb.authtree.getChecked('#LAY-auth-tree-index');
                var update = {id: obj.field.id, menusId: menusId};
                fb.api.policy.updateMenus(update, function () {
                    layer.closeAll();
                    layer.msg("分配成功");
                    renders.flush();
                });
                return;
            });


        },
        //渲染对象
        renders: {
            flush: function () {
                vars.table.flush();
            },
            layerAuthTree: function (data) {
                fb.use("authtree", function () {
                    var authtree = fb.authtree;
                    layer.open({
                        type: 1,
                        title: "菜单分配",
                        content: document.querySelector("#tmp-auth-form").innerHTML,
                        area: ['350px', '500px'],
                        success: function () {
                            fb.form.val('role-menu-form', data)
                            fb.api.menu.get("appsId=" + data.appsId.join(","), function (menuNodes) {
                                var menuList = methods.convertMenu(menuNodes);
                                var tree = methods.convertTree(menuList, data.menusId);
                                // 渲染时传入渲染目标ID，树形结构数据（具体结构看样例，checked表示默认选中），以及input表单的名字
                                authtree.render('#LAY-auth-tree-index', tree, {
                                    inputname: 'menusId[]',
                                    layfilter: 'lay-check-auth',
                                    openall: true,
                                    dblshow: true,
                                    autowidth: true,
                                });
                            });
                        }
                    });
                });
            },


            render: function (type) {
                if (sysTools.isDeveloper()) {
                    sysTools.renderAppSelect();
                }
                var config = {
                    el: "policy-table",
                    url: fb.api.policy.url,
                    fixHeightNumber: 300,
                    queryCache: false,
                    defines: [
                        {
                            head: "策略名称",
                            prop: "policy_name",
                            // width:200,
                            // fixed:"left"

                        }, {
                            head: "说明",
                            prop: "remark",
                            wordBreak: true,
                            // width: 200,
                        }, {
                            head: "类型",
                            prop: "policy_type",
                            replace: function (v, o) {
                                return v === ("SYSTEM") ? "系统" : ("自定义" + (sysTools.isDeveloper() ? ("(实例：" + o.instanceId + ")") : ""));
                            },

                        },
                        {
                            head: "创建人",
                            prop: "created_username",
                        }, {
                            head: "创建时间",
                            prop: "gmt_create",
                            type: "datetime",
                            width: 200
                        }, {
                            head: "最后修改时间",
                            prop: "gmt_modified",
                            type: "datetime",
                            width: 200
                        }
                    ],
                    handlesCondition: function () {
                        return methods.conditionHideOperation();
                    },
                    handles: [
                        {
                            edit: function (data) {
                                renders.box(false, data);
                            }
                        },
                        {
                            edit: function (data) {
                                renders.layerAuthTree(data);
                            },
                            name: "分配菜单",
                            color: "green"
                        },
                        {
                            edit: function (data) {
                                router.route({
                                    url: "/fastboot/pages/sys/permissions",
                                    pushState: {
                                        policy: data, searchForm: vars.table.getQueryObject()
                                    }
                                });
                            },
                            name: "分配权限",
                            color: "#a76d5a",
                            visible: function () {
                                return AppConfig.authorization.resourcesHandlerEnabled || false;
                            }
                        },
                        {
                            del: {
                                tip: "确定要删除吗？",
                                do: function (data) {
                                    fb.api.policy.delete(data.id, function () {
                                        layer.closeAll();
                                        layer.msg("删除成功");
                                        renders.flush();

                                    })
                                }
                            }
                        },

                    ]
                };
                vars.table = new DataTable(config);
            },
            box: function (isCreate, data) {

                var title = "添加";
                if (!isCreate) {
                    title = "修改";
                }
                layer.open({
                    type: 1,
                    title: title,
                    content: document.querySelector("#tmp-policy-form").innerHTML,
                    area: ['500px', '280px'],
                    success: function () {
                        sysTools.filterWmmFbAuth("DEVELOPER");
                        if (sysTools.isDeveloper()) {
                            sysTools.renderAppSelect("appsIdBox");
                        }
                        if (!isCreate) {
                            if(sysTools.isDeveloper()) {
                                fb.formSelects.value("appsIdBox", data.appsId);
                            }
                            fb.form.val('policy-form', data)
                        }
                    }
                });
            },

        },
    });
</script>